﻿using clab.Helper;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace clab
{
    public partial class LoginPhone : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            IP.Text = GetIP();
        }

        protected void Submit_Logins_Click(object sender, EventArgs e)
        {
            if (uname.Text == "")
            {
                Response.Write("<script>alert('请输入您的姓名!')</script>");
                return;
            }
            if (bgnumber.Text == "")
            {
                Response.Write("<script>alert('报告编号!')</script>");
                return;
            }
            if (yz.Text == "")
            {
                Response.Write("<script>alert('请输入验证码!')</script>");
                return;
            }
            if (String.Compare(Request.Cookies["yzmcode"].Value, yz.Text, true) != 0)
            {
                Response.Write("<script>alert('验证码错误!')</script>");
                return;
            }
            else
            {
                var sql = "select * from khbg where labid='" + bgnumber.Text + "' and username='" + uname.Text + "' and labyear='" + labyear.Text + "' ";
                var result = DbHelper.GetModel<dynamic>(sql);
                if (result != null)
                {
                    Session["username"] = uname.Text;
                    Session["bgnumber"] = bgnumber.Text;
                    Session["labyear"] = labyear.Text;
                    Session["phone"] = result.tel;
                    if (result.tel == "" || result.tel == null)
                    {
                        Response.Write("<script>alert('手机号码检测为空，请补全手机号码后获取验证码！');</script>");
                        Response.Redirect("tel.aspx");
                    }
                    else
                    {
                        getSMSCode(result.tel, uname.Text);
                        Response.Redirect("telverification.aspx");
                    }

                }
                else
                {
                    Response.Write("<script> alert('暫未找到相關信息,請確認輸入正確?');</script> ");
                    //Response.Redirect("http://c.laboratory.hk/");
                    return;
                }

            }
        }
        /// <summary>
        /// 调取短信api 发送短信给客户端
        /// </summary>
        /// <param name="phone"></param>
        public void getSMSCode(string phone, string name)
        {
            DateTime date = DateTime.Now;
            string years = date.Year.ToString();
            string moth = date.Month < 10 ? "0" + date.Month.ToString() : date.Month.ToString();
            string day = date.Day < 10 ? "0" + date.Day.ToString() : date.Day.ToString();
            string hour = date.Hour < 10 ? "0" + date.Hour.ToString() : date.Hour.ToString();
            string min = date.Minute < 10 ? "0" + date.Minute.ToString() : date.Minute.ToString();
            string userid = "zhenxnet";
            string password = "5463310";
            string title = name;
            string titles = name;

            title = HttpUtility.UrlEncode(title, System.Text.Encoding.GetEncoding("GB2312"));
            string clsid = "w" + years.Substring(0, 2) + moth + day + hour + min + years + moth + day + "z";//"w"&left(yyear,2)&""&ymonth&""&yday&""&yhour&""&yminute&""&right(now(),1)&""
            string vtime = years + moth + day + hour + min;    //  & yyear & "" & ymonth & "" & yday & "" & yhour & "" & yminute & "";
            string code = RandomNumHelper.getRandomNum(6);//6位随机数字
            string strmd5 = userid + password + clsid + vtime;
            string userstr = FormsAuthentication.HashPasswordForStoringInConfigFile(strmd5, "MD5").ToLower();//md5(""&userid&""&password&""&clsid&""&vtime&"")
            string website = "http://c.laboratory.hk/";
            string msgContent = titles + "您好,手机验证码是" + code + ",查询网址:" + website + "【 香港化验所 】";
            msgContent = HttpUtility.UrlEncode(msgContent, System.Text.Encoding.GetEncoding("GB2312"));
            // "http://api.sms.pc51.com/?action=send&phonenum=" & rs("tel") & "&title=" & title & "&msg=" & msgss & "&dtime=0&clsid=" & clsid & "&userid=" & userid & "&userstr=" & userstr & "&vtime=" & vtime & """

            string url = "http://api.sms.pc51.com/?action=send&phonenum=" + phone + "&title=" + title + "&msg=" + msgContent + "&dtime=0&clsid=" + clsid + "&userid=" + userid + "&userstr=" + userstr + "&vtime=" + vtime;
            Session["code"] = code;
            HttpPostSendCode(url, code);
        }

        public void HttpPostSendCode(string url, string code)
        {
            string result = "";
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
            webRequest.Method = "POST";
            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.ContentLength = 0;
            try
            {
                HttpWebResponse HttpWResp = (HttpWebResponse)webRequest.GetResponse();

                Stream myStream = HttpWResp.GetResponseStream();
                StreamReader sr = new StreamReader(myStream, Encoding.UTF8);
                StringBuilder stringBuilder = new StringBuilder();
                while (-1 != sr.Peek())
                {
                    stringBuilder.Append(sr.ReadLine());
                }
                result = stringBuilder.ToString();
                if (result.IndexOf("<returncode>200</returncode>") > -1)
                {

                    var sqlUpdate = " update khbg set khyzm='" + code + "' where username='" + uname.Text + "' and labid='" + bgnumber.Text + "'";
                    var results = DbHelper.Execute(sqlUpdate);
                    Response.Write("<script>alert('驗證碼已經發送！');</script>");

                }
                else
                {
                    Response.Write("<script>alert('驗證碼发送失败，请联系管理员！！');</script>");
                }
            }
            catch (Exception ex)
            {
                Response.Write("<script>alert('" + ex.Message + "');</script>");
            }
        }

        public static string GetIP()
        {
            //如果客户端使用了代理服务器，则利用HTTP_X_FORWARDED_FOR找到客户端IP地址
            string userHostAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]==null?"" 
                : HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString().Split(',')[0].Trim();
            //否则直接读取REMOTE_ADDR获取客户端IP地址
            if (string.IsNullOrEmpty(userHostAddress))
            {
                userHostAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }
            //前两者均失败，则利用Request.UserHostAddress属性获取IP地址，但此时无法确定该IP是客户端IP还是代理IP
            if (string.IsNullOrEmpty(userHostAddress))
            {
                userHostAddress = HttpContext.Current.Request.UserHostAddress;
            }
            //最后判断获取是否成功，并检查IP地址的格式（检查其格式非常重要）
            if (!string.IsNullOrEmpty(userHostAddress) && IsIP(userHostAddress))
            {
                return userHostAddress;
            }
            return "127.0.0.1";
        }
        /// <summary>
        /// 检查IP地址格式
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public static bool IsIP(string ip)
        {
            return System.Text.RegularExpressions.Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
        }
    }
}